// @author Tim Major
// @customized Ben Loveridge
// @revision 20071004-1545

var curTab;
var returnURL;
var plScrolling = true;
var _LoadQVT;
// extract domain name for geoserver.  Just in case matching fails, use a default value
// var domain = window.location.href.match(/:\/\/([^\/\?$]+\.)*([^\/\?$]+\.[^\/\?$]+)/)[2] || "webcindario.com";
var d = window.location.href.match(/:\/\/([^\/\?$]+)/)[1].split('.') ;
if(d[d.length-2] == 'com' && d[d.length-1].length==2)
	var domain = d[d.length-3]+'.'+d[d.length-2]+'.'+d[d.length-1];
else
	var domain = d[d.length-2]+'.'+d[d.length-1];
var geoserverUrl = "http://gksrv."webcindario.com"/esmasgeo";
var gapClipUrl = "http://movelive5.cdn.movenetworks.com/esmas/clips/esmasblock/output.qmx" // content to use for a gap show
var blockClipUrl = "http://movelive5.cdn.movenetworks.com/esmas/clips/esmasblock/output.qmx" // content to use when geofiltered out
// Overrides blockClipUrl based on first match of an expression to the user's location.
var blockClipMap = {
    "[*|*|mex|*]":"http://movelive5.cdn.movenetworks.com/esmas/clips/partidonodisp/output.qmx",
    "[*|*|usa|*]":"http://movelive5.cdn.movenetworks.com/esmas/clips/servicionodisp/output.qmx"
}
var geoOverrideFilter = "[*|*|dolmandia|*]";

function CustomWindowLoaded(){
    // Wrap MN.QVT.Load so that we can do geofiltering and gap replacement
	_LoadQVT = MN.QVT.LoadQVT;
	MN.QVT.LoadQVT = LoadAndProcessQVT;

	// Initialize the Geofiltering
	log("GEOFILTERING COOKIE: " + MN.Cookie.Get("videovalid"));
	MN.Geo.Init(geoserverUrl);
}

// Overwrites blockClipUrl with url in fillerMap that matches based on user's location
function ProcessBlockClipMap(){
    for(var entry in blockClipMap)
    {
        var expr = entry;
        var url = blockClipMap[expr];
        if(MN.Geo.IsUserAllowed(expr))
        {
            blockClipUrl = url;
        }
    }
}

function CustomPlayerLoaded(player){
	$('pageLoading').style.display = 'block';
	MN.Event.Observe($('mn_channel_dropdown'), 'change', ChannelDropdownChanged)
	try{
		if(window.opener){
			returnURL = window.opener.location.href;
			MN.Event.Observe($('back_home'), 'click', ReturnToHome);
		}
	}
	catch(e){
	}
	MN.TP.InitS2F();

	MN.Event.Observe($('mn_pl_scroll_up'), 'mousedown', function(){plScrolling = true;MN.TP.qmp.playlist.ScrollUp();});
	MN.Event.Observe($('mn_pl_scroll_up'), 'mouseup', function(){plScrolling = true;} );
	MN.Event.Observe($('mn_pl_scroll_up'), 'mouseout', function(){plScrolling = true;} );

	MN.Event.Observe($('mn_pl_scroll_down'), 'mousedown', function(){plScrolling = true;MN.TP.qmp.playlist.ScrollDown();});
	MN.Event.Observe($('mn_pl_scroll_down'), 'mouseup', function(){plScrolling = true;} );
	MN.Event.Observe($('mn_pl_scroll_down'), 'mouseout', function(){plScrolling = true;} );
}

function ChannelDropdownChanged(evt) {
	var dd = $('mn_channel_dropdown');
	for(i=0; i < dd.length; i++){
		if(dd[i].selected)
			MN.TP.SwitchToChannel(dd[i].value)
	}
}

// Wrapper for MN.QVT.LoadQVT that does geofiltering and gap replacement
function LoadAndProcessQVT(url, doneCB)
{
    var skipGeo = true;

    if(geoOverrideFilter)
    {
        var f = MN.Geo.MakeFilteringFunc(geoOverrideFilter);
        var loc = MN.Cookie.Get("videovalid");
        if(f(loc)) skipGeo = true;
    }

	_LoadQVT(url, function(url, result, respHeaders){
		qvtObj = MN.EvalJSON(result);
		ProcessBlockClipMap();

		if(skipGeo)
		{
		    log('SKIPPING GEOFILTERING QVT')
		}
		else
		{
		    log('GEOFILTERING QVT ' + url)
		    MN.Geo.GeofilterQVT(qvtObj, blockClipUrl);
		}

		log('FILLING GAP SHOWS IN QVT ' + url);
		MN.QVTEdit.SetEmptyShowsContentURL(qvtObj, gapClipUrl);
		// Pass the processed QVT on to the original callback
		doneCB(url, JSON.stringify(qvtObj), respHeaders);
	})
}

CustomPlPopulated = function(){
		for(var i = 0; i < 50; i++){ //esmas should never have more than 50 clips for any given day
			if($('clip'+i)) {
				MakeClipObserve($('clip'+i));
			}
		}
}
MakeClipObserve = function(showBox) {
	MN.Event.Observe(showBox, 'click', function(){ OnClipClicked(showBox.getAttribute("shownumber")) });
}

OnClipClicked = function(showNum) {
	//MN.TP.customStartStop = true;
	//MN.TP.stopPos = -1;
	//MN.TP.startPos = -1;

	if(MN.TP.curChnl.name.indexOf('proyecto40') != -1){
		$('mn_player').style.visibility = 'visible';
		//$('proyectoOverlay').style.display = 'none';
		$('proyectoOverlay').style.left = '-9000px';
		$('mn_show_title_center').style.textIndent = '';
		$('mn_duration').style.textIndent = '';
		$('mn_status').style.textIndent = '';
		$('mn_pause').className = $('mn_pause').className.replace('disabled','');
		$('mn_play').className = $('mn_play').className.replace('disabled','');
		$('mn_rewind').className = $('mn_rewind').className.replace('disabled','');
		$('mn_fast_forward').className = $('mn_fast_forward').className.replace('disabled','');
	}

	MN.TP.curShow = showNum;
	//get the proper playlist div
	var showBoxes = $('mn_playlist').childNodes;
	for (i = 0; i < showBoxes.length; i++){
		if(showBoxes[i].nodeType == 1){
			showBoxes = showBoxes[i].childNodes;
			break;
		}
	}

	//make sure the proper date is selected in dropdown
	var dd = $('mn_content_dropdown').options;
	for(var i = 0; i < dd.length; i++){
		if(dd[i].value == MN.TP.qmp.CurrentQVT().GetSource()){
			dd[i].selected = true;
			break;
		}
	}

	//remove existing highlights, if any
    for(var i = 0; i < showBoxes.length; i++){
		if(showBoxes[i].getAttribute("playing") == "true"){
			log('remove highlight: ',i)
			showBoxes[i].className = showBoxes[i].className.replace('mn_highlight', '');
			showBoxes[i].setAttribute("playing","false");
		}
	}

	//do new highlight
	log('highlight: ',showNum);
	var showBox;
	for (i = 0; i < showBoxes.length; i++){
		if (showBoxes[i].getAttribute("shownumber") == showNum){
			showBox = showBoxes[i];
			break;
		}
	}
	showBox.className += ' mn_highlight';
	showBox.setAttribute("playing","true");
}

CustomShowLoaded = function(showNum,title){
	var position = MN.TP.qmp.CurrentPosition();
	var duration = MN.TP.qmp.CurrentQVT().Duration();
	var showURL = MN.TP.qmp.CurrentQVT().GetSource();
	MN.TP.curURL = (MN.TP.onLive || MN.TP.showChangedOnClick) ? showURL : MN.TP.curURL;

	if($('pageLoading').style.display == 'block')
		$('pageLoading').style.display = 'none';

	if(showNum == 0 && MN.TP.stopPos == -1 && !MN.TP.onLive && MN.TP.curURL != showURL) { //first show should only have -1 if live or came from crossing over midnight
		MN.TP.curShow = showNum;
		MN.TP.startPos = MN.TP.qmp.CurrentQVT().StartTime(showNum) + .1;
		MN.TP.stopPos = MN.TP.qmp.CurrentQVT().StopTime(showNum) - .1;

		//make sure the right date is selected in the date dropdown
		var curDateIndex = $('mn_content_dropdown').selectedIndex;
		$('mn_content_dropdown').selectedIndex = (curDateIndex > 0) ? curDateIndex-1 : 0;

		MN.TP.qmp.Play(MN.TP.qmp.CurrentQVT().GetSource(), MN.TP.startPos, MN.TP.stopPos);
		MN.TP.curURL = showURL;
	}

	if(MN.TP.onLive){
		//MN.TP.showChangedOnClick = false;
		MN.TP.startPos = MN.TP.qmp.CurrentQVT().StartTime(showNum) + .1; //reset startPos ; stopPos was set when they clicked GoLive or changed chnl
		if(MN.TP.curChnl.name.indexOf('proyecto40') != -1){
			MN.TP.qmp.Stop();
		}
	}
	if(MN.TP.stopPos == -1){ //check stopPos, not onLive, because last show of VOD day is given -1 so it continues to next day
		MN.TP.qmp.SetAutoPlayNext(true);
	}
	else{
		MN.TP.qmp.SetAutoPlayNext(false);
	}

	if(MN.TP.qmp.scrubbing || MN.TP.scrubRate != 0) { //they are scrubbing, look deeper to check what should happen
		if(MN.TP.scrubRate < 0) {//rewinding; NEVER rewind past beginning of show
			MN.TP.Pause();
			if(MN.TP.onLive){
				setTimeout('MN.TP.qmp.CurrentPosition(MN.TP.startPos)',1000);
			}
			else{
				setTimeout('MN.TP.Play(MN.TP.qmp.CurrentQVT().GetSource(),MN.TP.startPos,MN.TP.stopPos)',1000);
			}
		}
		else{ //fast forwarding; ignore if live
			/*if(!MN.TP.onLive && MN.TP.showChangedOnClick){ //if still scrubbing somehow after a click, stop scrubbing and start from beginning
				MN.TP.Pause();
				setTimeout('MN.TP.Play(MN.TP.qmp.CurrentQVT().GetSource(),MN.TP.startPos,MN.TP.stopPos)',1000);
			}
			else*/ if(!MN.TP.onLive && !MN.TP.showChangedOnClick) { //if scrubbed past end of VOD show, take them back 10 seconds or so
				if(nextDayStart != null && nextDayStop != null)
					ContinueToNextDay(MN.QMP.PS.Playing, MN.QMP.PS.MediaEnded);
				else{
					MN.TP.Pause();
					setTimeout('MN.TP.qmp.CurrentPosition(MN.TP.stopPos - 10)',1000);
					setTimeout('MN.TP.Pause()',1000);
				}
			}
		}
	}
	if(MN.TP.stopPos != -1 && position > MN.TP.stopPos){ //if they somehow watched (not scrubbed) past end of show, take them back 10 seconds
		if(nextDayStart != null && nextDayStop != null)
			ContinueToNextDay(MN.QMP.PS.Playing, MN.QMP.PS.MediaEnded);
		else{
			MN.TP.qmp.CurrentPosition(MN.TP.stopPos - .5);
			setTimeout('MN.TP.Pause()',250);
		}
	}

	nextDayStart = nextDayStop = nextDayQVT = null;
	MN.Event.StopObserving(MN.TP.qmp, 'PlayStateChanged', ContinueToNextDay);
	CheckNextDayShow(MN.TP.showChangedOnClick);
	MN.TP.showChangedOnClick = false; //always set false after the show has changed the first time
}

/*setStop = function(){
		MN.TP.qmp.player.SetStopPosition(MN.TP.qmp.CurrentQVT().StopTime(MN.TP.qmp.CurrentShow()));
}*/

CheckNextDayShow = function(changedOnClick){
	if(!changedOnClick)
		return false;

	var lastShow = false;
	var thisQVT = MN.TP.qmp.CurrentQVT();
	var curShow = MN.TP.qmp.CurrentShow();
	if(curShow == thisQVT.meta.shows.length-1 || curShow == thisQVT.meta.shows.length-2 && thisQVT.meta.shows[curShow+1].isGap)
		lastShow = true;
	//only set stuff up if this isn't today's QVT and curShow is lastShow
	if(thisQVT.GetTimelineNow() >= thisQVT.duration && lastShow){
		var qvt = MN.QVT.AcquireQVT(thisQVT.NextURL());
		if(qvt.IsLoading())
			MN.Event.Observe(qvt, 'TimelineLoaded', NextDayQVTLoaded);
		else
			NextDayQVTLoaded(qvt);
	}
};
var nextDayStart = null;
var nextDayStop = null;
var nextDayQVT = null;
NextDayQVTLoaded = function(nextQVT){
	var curShow = MN.TP.qmp.CurrentQVT().meta.shows[MN.TP.qmp.CurrentShow()];
	// if(nextQVT.meta.shows[0].title == curShow.title && nextQVT.meta.shows[0].desc == curShow.desc){
	if(nextQVT.meta.shows[0].title == curShow.title){
		nextDayStart = nextQVT.meta.shows[0].tlStartTime;
		nextDayStop = nextQVT.meta.shows[0].tlStopTime;
		nextDayQVT = nextQVT.GetSource();
		MN.Event.Observe(MN.TP.qmp, 'PlayStateChanged', ContinueToNextDay);
	}
	else{
		nextDayStart = nextDayStop = nextDayQVT = null;
	}
};
ContinueToNextDay = function(oldPS, newPS){
	if(newPS == MN.QMP.PS.MediaEnded){
		MN.TP.startPos = nextDayStart + .1;
		MN.TP.stopPos = nextDayStop - .1;
		MN.TP.qmp.Play(nextDayQVT, nextDayStart, nextDayStop);
		MN.Event.Observe(MN.TP.qmp, 'PlayStateChanged', HighlightNextDay);
	}
};
HighlightNextDay = function(oldPS, newPS){
	if(newPS == MN.QMP.PS.Playing){
		MN.TP.Play();
		setTimeout('MN.TP.Play()',1000);
		MN.Event.StopObserving(MN.TP.qmp, 'PlayStateChanged', HighlightNextDay);
		OnClipClicked(0);
	}
};